package com.yuanda.erp9.syn.scanner;

import com.yuanda.erp9.syn.contant.RateCalculateConstants;
import com.yuanda.erp9.syn.entity.CmsBrandsTempEntity;
import com.yuanda.erp9.syn.entity.CmsSuppliersTempEntity;
import com.yuanda.erp9.syn.enums.CachePrefixEnum;
import com.yuanda.erp9.syn.pojo.StandardPartnumbersForPluginDataPojo;
import com.yuanda.erp9.syn.service.erp9.BrandService;
import com.yuanda.erp9.syn.service.erp9.SupplierService;
import com.yuanda.erp9.syn.service.rate.ExchangeRatesService;
import com.yuanda.erp9.syn.service.rate.StandardPartnumbersForPluginService;
import com.yuanda.erp9.syn.util.CacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.common.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName MyCommandLineRunner
 * @Description 异步启动 帮助我们
 * @Date 2022/11/18
 * @Author myq
 */
@Component
@Slf4j
public class CacheCommandLineRunner implements CommandLineRunner {
    @Autowired
    private BrandService brandService;

    @Autowired
    private SupplierService supplierService;

    @Autowired
    private ExchangeRatesService exchangeRatesService;

    @Autowired
    private StandardPartnumbersForPluginService standardPartnumbersForPluginService;

    @Override
    public void run(String... args) {
        CacheUtil.Cache brands = CacheUtil.init(CachePrefixEnum.BRAND.getKey());
        List<CmsBrandsTempEntity> cmsBrandsTempEntities = brandService.selectList();
        if (!CollectionUtils.isEmpty(cmsBrandsTempEntities)) {
            Map<String, Integer> brandMap = cmsBrandsTempEntities.stream().collect(Collectors.toMap(CmsBrandsTempEntity::getName, CmsBrandsTempEntity::getBrandid, (k1, k2) -> k2));
            brandMap.forEach((k, v) -> {
                // 所有小写
                brands.put(k.toLowerCase(), v);
            });
        }
        log.info("******************品牌型号初始化完毕******************");
        brands.cacheIsValid = true;

        CacheUtil.ObjectCache rsHKData = CacheUtil.objectInit(CachePrefixEnum.RS_HK_DATA.getKey());
        rsHKData.cacheIsValid = true;

        CacheUtil.Cache supplier = CacheUtil.init(CachePrefixEnum.SUPPLIERS.getKey());
        List<CmsSuppliersTempEntity> cmsSuppliersTempEntities = supplierService.selectList();
        if (!CollectionUtils.isEmpty(cmsSuppliersTempEntities)) {
            Map<String, Integer> supplierMap = cmsSuppliersTempEntities.stream().filter(e -> !StringUtils.isEmpty(e.getName())).collect(Collectors.toMap(CmsSuppliersTempEntity::getName, CmsSuppliersTempEntity::getSupplierid, (k1, k2) -> k2));
            supplierMap.forEach((k, v) -> {
                // 所有小写
                supplier.put(k.toLowerCase(), v);
            });
        }
        log.info("******************生产厂商初始化完毕******************");
        supplier.cacheIsValid = true;

        CacheUtil.ObjectCache exchangeRates = CacheUtil.objectInit(CachePrefixEnum.EXCHANGE_RATES.getKey());
        BigDecimal effectiveData = exchangeRatesService.getEffectiveData();
        if (effectiveData != null) {
            Map<String, Object> supplierMap = new HashMap<>();
            supplierMap.put(CachePrefixEnum.EXCHANGE_RATES.getKey(), effectiveData);
            exchangeRates.putAll(supplierMap);
        }
        log.info("******************汇率信息初始化完毕******************");
        exchangeRates.cacheIsValid = true;

        CacheUtil.ObjectCache standardPartnumbersForPlugin = CacheUtil.objectInit(CachePrefixEnum.STANDARD_PARTNUMBER_SFORPLUGIN.getKey());
        List<StandardPartnumbersForPluginDataPojo> standardPartnumbersForPluginEntities = standardPartnumbersForPluginService.selectList();
        if (!CollectionUtils.isEmpty(standardPartnumbersForPluginEntities)) {
            Map<String, Object> map = new HashMap<>();
            for (StandardPartnumbersForPluginDataPojo standardPartnumbersForPluginDataPojo : standardPartnumbersForPluginEntities) {
                String partNumber = standardPartnumbersForPluginDataPojo.getPartNumber();
                // map.put(manufacturer.toLowerCase().trim() + partNumber.toLowerCase().trim(), getRateMap(standardPartnumbersForPluginDataPojo));
                map.put(partNumber.toLowerCase().trim(), getRateMap(standardPartnumbersForPluginDataPojo));
            }
            standardPartnumbersForPlugin.putAll(map);
        }
        log.info("******************器件信息汇率初始化完毕******************");
        standardPartnumbersForPlugin.cacheIsValid = true;
    }

    /**
     * 获取费率map
     *
     * @param standardPartnumbersForPluginDataPojo 型号费率数据
     * @return 返回费率map
     */
    private Map<String, String> getRateMap(StandardPartnumbersForPluginDataPojo standardPartnumbersForPluginDataPojo) {
        Map<String, String> rateMap = new HashMap<>();
        if (standardPartnumbersForPluginDataPojo.getVatRate() != null) {
            String vatRate = BigDecimal.valueOf(standardPartnumbersForPluginDataPojo.getVatRate()).setScale(7, BigDecimal.ROUND_HALF_UP).toPlainString();
            rateMap.put(RateCalculateConstants.VATRATE_FIELD, vatRate);
        } else {
            rateMap.put(RateCalculateConstants.VATRATE_FIELD, RateCalculateConstants.ZERO);
        }

        if (standardPartnumbersForPluginDataPojo.getTariffRate() != null) {
            String tariffRate = BigDecimal.valueOf(standardPartnumbersForPluginDataPojo.getTariffRate()).setScale(7, BigDecimal.ROUND_HALF_UP).toPlainString();
            rateMap.put(RateCalculateConstants.TARIFFRATE_FIELD, tariffRate);
        } else {
            rateMap.put(RateCalculateConstants.TARIFFRATE_FIELD, RateCalculateConstants.ZERO);
        }

        if (standardPartnumbersForPluginDataPojo.getExciseTaxRate() != null) {
            String exciseTaxRate = BigDecimal.valueOf(standardPartnumbersForPluginDataPojo.getExciseTaxRate()).setScale(7, BigDecimal.ROUND_HALF_UP).toPlainString();
            rateMap.put(RateCalculateConstants.EXCISETAXRATE_FIELD, exciseTaxRate);
        } else {
            rateMap.put(RateCalculateConstants.EXCISETAXRATE_FIELD, RateCalculateConstants.ZERO);
        }

        if (standardPartnumbersForPluginDataPojo.getCiqPrice() != null) {
            String ciqPrice = BigDecimal.valueOf(standardPartnumbersForPluginDataPojo.getCiqPrice()).setScale(7, BigDecimal.ROUND_HALF_UP).toPlainString();
            rateMap.put(RateCalculateConstants.CIQPRICE_FIELD, ciqPrice);
        } else {
            rateMap.put(RateCalculateConstants.CIQPRICE_FIELD, RateCalculateConstants.ZERO);
        }

        if (standardPartnumbersForPluginDataPojo.getAddedTariffRate() != null) {
            String addedTariffRate = BigDecimal.valueOf(standardPartnumbersForPluginDataPojo.getAddedTariffRate()).setScale(7, BigDecimal.ROUND_HALF_UP).toPlainString();
            rateMap.put(RateCalculateConstants.ADDEDTARIFFRATE_FIELD, addedTariffRate);
        } else {
            rateMap.put(RateCalculateConstants.ADDEDTARIFFRATE_FIELD, RateCalculateConstants.ZERO);
        }

        // 是否3c认证
        if (standardPartnumbersForPluginDataPojo.getCcc() != null) {
            rateMap.put(RateCalculateConstants.CCC_FIELD, standardPartnumbersForPluginDataPojo.getCcc().toString());
        }else{
            rateMap.put(RateCalculateConstants.CCC_FIELD, RateCalculateConstants.ZERO);
        }

        // 是否禁运
        if (standardPartnumbersForPluginDataPojo.getEmbargo() != null) {
            rateMap.put(RateCalculateConstants.EMBARGO_FIELD, standardPartnumbersForPluginDataPojo.getEmbargo().toString());
        }else{
            rateMap.put(RateCalculateConstants.EMBARGO_FIELD, RateCalculateConstants.ZERO);
        }

        // eccn
        if (!Strings.isNullOrEmpty(standardPartnumbersForPluginDataPojo.getEccn())) {
            rateMap.put(RateCalculateConstants.ECCN_FIELD, standardPartnumbersForPluginDataPojo.getEccn());
        }else{
            rateMap.put(RateCalculateConstants.ECCN_FIELD, "");
        }

        return rateMap;
    }
}